/*
 * Copyright (c) 2022, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-08-29     xu     first version
 */

#include <rtthread.h>
#include <stdlib.h>
#include <fal.h>
#include <spi_flash_sfud.h>
#include "drv_spi.h"

#define SPI_W25Q_BUS_NAME "spi3"
#define SPI_W25Q_DEV_NAME "spi30"
#define SPI_W25Q_CS_PORT GPIOA
#define SPI_W25Q_CS_PIN GPIO_PIN_15
#define SPI_FLASH_DEV_NAME FAL_USING_NOR_FLASH_DEV_NAME

static struct rt_spi_device *spi_dev = RT_NULL;

static int flash_init()
{
    // attach w25q spi flash device
    rt_err_t err = rt_hw_spi_device_attach(SPI_W25Q_BUS_NAME, SPI_W25Q_DEV_NAME, SPI_W25Q_CS_PORT, SPI_W25Q_CS_PIN);
    if (err != RT_EOK)
    {
        rt_kprintf("SPI device %s attach FAIL!\n", SPI_W25Q_DEV_NAME);
        return 1;
    }

    spi_dev = (struct rt_spi_device *)rt_device_find(SPI_W25Q_DEV_NAME);
    if (spi_dev != RT_NULL)
    {
        rt_kprintf("find %s OK!\n", SPI_W25Q_DEV_NAME);
    }
    else
    {
        rt_kprintf("find %s FAILED!\n", SPI_W25Q_DEV_NAME);
    }

    // struct rt_spi_configuration spi_config = {0};
    // spi_config.data_width = 8;
    // spi_config.max_hz = 1 * 1000 * 1000;
    // spi_config.mode = RT_SPI_MASTER | RT_SPI_MODE_0 | RT_SPI_MSB;
    // rt_kprintf("configure %s ...\n", SPI_W25Q_DEV_NAME);
    // rt_spi_configure(spi_dev, &spi_config);

    // probe partition on spi flash
    if (RT_NULL == rt_sfud_flash_probe(SPI_FLASH_DEV_NAME, SPI_W25Q_DEV_NAME))
    {
        rt_kprintf("Probe %s FAIL!\n", SPI_FLASH_DEV_NAME);
        return 1;
    }

    fal_init(); // after flash device probe
    rt_kprintf("%s done!\n", __func__);
    return 0;
}
INIT_ENV_EXPORT(flash_init);

static int flash_cs(int argc, char *argv[])
{
    int value = 0;
    if (argc <= 1)
    {
        rt_kprintf("usage: %s [0|1]\n", __func__);
        return -1;
    }

    value = atoi(argv[1]);
    if (value)
    {
        GPIO_SetBits(SPI_W25Q_CS_PORT, SPI_W25Q_CS_PIN);
    }
    else
    {
        GPIO_ClearBits(SPI_W25Q_CS_PORT, SPI_W25Q_CS_PIN);
    }
    return 0;
}
MSH_CMD_EXPORT(flash_cs, "Flash CS test");
